package com.saturn.app.utils;

import java.util.List;

import org.apache.log4j.Logger;

import com.saturn.auth.Resource;

public class JSONUtils {
	private static Logger logger = LogManager.getLogger(LogManager.LOG_KEY_APP);

	private JSONUtils() {

	}

	public static String getDataGridJSON(int total, List<?> rows) {
		return getDataGridJSON(total, rows, null);
	}

	public static String getDataGridJSON(int total, List<?> rows, List<?> footer) {
		StringBuffer buffer = new StringBuffer();

		buffer.append("{");

		buffer.append("\"total\":" + total + ",");
		buffer.append("\"rows\":" + rows);
		if (footer != null) {
			buffer.append(",\"footer\":" + footer);
		}

		buffer.append("}");
		logger.debug("DataGridJSON:" + buffer.toString());
		return buffer.toString();
	}

	public static String getTreeJSON(List<Resource> rows) {
		String json = generateTreeJSON(rows);
		logger.debug("DataGridJSON:" + json);
		return json;
	}
	
	public static String generateTreeJSON(List<Resource> rows) {

		StringBuffer buffer = new StringBuffer();
		buffer.append("[");

		for (Resource resource : rows) {
			buffer.append("{");
			buffer.append("\"id\":" + "\"" + resource.getId() + "\"" + ",");
			buffer.append("\"text\":" + "\"" + resource.getName() + "\"" + ",");
			List<Resource> child = resource.getChild();
			if (child != null && !child.isEmpty()) {
				buffer.append("\"state\":" + "\"closed\"" + ",");
			}
//			buffer.append("\"iconCls\":\"icon-author\",");
			if (resource.getPath() != null) {
				buffer.append("\"attributes\":{\"path\":" + "\""
						+ resource.getPath() + "\"" + "}");
			} else {
				buffer.append("\"attributes\":null" );
			}
			
			buffer.append(", \"children\" : ").append(generateTreeJSON(child));
			buffer.append("},");
		}
		buffer.append("]");
		String json = buffer.toString().replaceFirst(",]", "]");
		return json;
	}
}
